package com.cruel_wandering.wifi_geo_predictor;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.cruel_wandering.wifi_geo_predictor.wifi_simulation.MyWifiInfo;
import com.cruel_wandering.wifi_geo_predictor.wifi_simulation.MyWifiManager;
import com.cruel_wandering.wifi_geo_predictor.wifi_simulation.WifiManagerSimpleSimulator;
import com.cruel_wandering.wifi_geo_predictor.wifi_simulation.WifiManagerWrapper;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainScreen extends Activity implements
SharedPreferences.OnSharedPreferenceChangeListener
{

	static private final String TAG = "MainScreen";	
	//private WifiManager wifiMan;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);

	    SharedPreferences prefs =
	        PreferenceManager.getDefaultSharedPreferences(this);
	    prefs.registerOnSharedPreferenceChangeListener(this);

	    if (!prefs.getBoolean(Preferences.WIFI_SIMULATOR, true))
	    {
		    Logger.getInstance(this).log(TAG, "Using Android's default Wifi Manager");
		    MyWifiManager.setManager(new WifiManagerWrapper(this));
	    }
	    else
	    {
	    	Logger.logAndToast(this, TAG, "Using Wifi Manager Simulator");
	    	MyWifiManager.setManager(
	    		new WifiManagerSimpleSimulator(this, "dummy_name", true));
	    	MyWifiManager wifiMan = MyWifiManager.getManager();
	    	wifiMan.setWifiEnabled(true);
	    }

	    Logger.getInstance(this).log(TAG, "Creating Oracle and starting it");
	    startService(new Intent(this, Oracle.class));

	     
	    
	    
	    
	    print_prefs(prefs);

	    /* Garbage */
	    final Button button = (Button) findViewById(R.id.cellIdLoc);
	    button.setOnClickListener(new OnClickListener(){
	    	public void onClick(View v){
	    	     String urlString = "http://www.google.com/glm/mmap";            
	    	     
	    	        //---open a connection to Google Maps API---
	    	        URL url;
			try {
					url = new URL(urlString);
	    	        URLConnection conn = url.openConnection();
	    	        HttpURLConnection httpConn = (HttpURLConnection) conn;        
	    	        httpConn.setRequestMethod("POST");
	    	        httpConn.setDoOutput(true); 
	    	        httpConn.setDoInput(true);
	    	        httpConn.connect(); 
	    	        
	    	        //---write some custom data to Google Maps API---
	    	        OutputStream outputStream = httpConn.getOutputStream();
	    	        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
	    	        dataOutputStream.writeShort(21);
	    	        dataOutputStream.writeLong(0);
	    	        dataOutputStream.writeUTF("en");
	    	        dataOutputStream.writeUTF("Android");
	    	        dataOutputStream.writeUTF("1.0");
	    	        dataOutputStream.writeUTF("Web");
	    	        dataOutputStream.writeByte(27);
	    	        dataOutputStream.writeInt(0);
	    	        dataOutputStream.writeInt(0);
	    	        dataOutputStream.writeInt(3);
	    	        dataOutputStream.writeUTF("");

	    	        
	    	        TelephonyManager tm  = 
	    	            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
	    	        GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
	    	        int cellID = location.getCid();
	    	        int lac = location.getLac();
	    	        
	    	        dataOutputStream.writeInt(cellID);  
	    	        dataOutputStream.writeInt(lac);     

	    	        dataOutputStream.writeInt(0);
	    	        dataOutputStream.writeInt(0);
	    	        dataOutputStream.writeInt(0);
	    	        dataOutputStream.writeInt(0);
	    	        dataOutputStream.flush();        
	    	        
	    	        //---get the response---
	    	        InputStream inputStream = httpConn.getInputStream();  
	    	        DataInputStream dataInputStream = new DataInputStream(inputStream);
	    	        
	    	        //---interpret the response obtained---
	    	        dataInputStream.readShort();
	    	        dataInputStream.readByte();
	    	        int code = dataInputStream.readInt();
	    	        String msg="";
	    	        if (code == 0) {
	    	           double lat = (double) dataInputStream.readInt() / 1000000D;
	    	           double lng = (double) dataInputStream.readInt() / 1000000D;
	    	           msg = "lat: "+lat+"     lng: "+lng;
	    	        }else{
	    	        	msg = "Error in the location computation by CellId.";
	    	        }
	    
	    	        Toast.makeText(MainScreen.this, msg,Toast.LENGTH_LONG).show();
	    	        
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		}
	    });  

	    final Button button2 = (Button) findViewById(R.id.wifiInfo);
	    button2.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	MyWifiManager wm = MyWifiManager.getManager();
	        	String msg = "There is no connection info (info = null)";
	        	MyWifiInfo info = wm.getConnectionInfo();

	        	if (info != null)
	        	{
	        		msg = "YEAH!!!! info: " + info;
	        		msg += "\n" + " SSID: " + (info.getSSID() == null ? "(null)" : info.getSSID());
	        		msg += "\n" + " BSSID: " + (info.getBSSID() == null ? "(null)" : info.getBSSID());
	        		msg += "\n" + " IP: " + info.getIpAddress();
	        	  msg += "\n" + " Speed: " + info.getLinkSpeed();
	        	}
            // Perform action on clicks
	          Toast.makeText(MainScreen.this, msg, Toast.LENGTH_LONG).show();
	        }
	    });		

		//WifiScaner wifiScaner = new WifiScaner( wifiMan );
		//registerReceiver(wifiScaner, new IntentFilter(
		//			WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));	
		//wifiMan.startScan();
	    
	}

	 private void print_prefs(SharedPreferences prefs)
	  {
	        {
	          TextView tv = (TextView)findViewById(R.id.debug_mode);
	          tv.setText(Preferences.getFieldName(Preferences.DEBUG_MODE) + ": " +
	                  (prefs.getBoolean(Preferences.DEBUG_MODE, false) ? "yes" : "no"));
	        }
	        {
	          TextView tv = (TextView)findViewById(R.id.wifi_sim);
	          tv.setText(Preferences.getFieldName(Preferences.WIFI_SIMULATOR) + ": " +
	        		  (prefs.getBoolean(Preferences.WIFI_SIMULATOR, false) ? "yes" : "no"));
	        }
	        {
	          TextView tv = (TextView)findViewById(R.id.pref_use_GPS);
	          tv.setText(Preferences.getFieldName(Preferences.MAY_USE_GPS) + ": " +
	                  (prefs.getBoolean(Preferences.MAY_USE_GPS, false) ? "yes" : "no"));
	        }
	        {
	          TextView tv = (TextView)findViewById(R.id.pref_use_CellID);
	          tv.setText(Preferences.getFieldName(Preferences.MAY_USE_CELLID) + ": " +
	                  (prefs.getBoolean(Preferences.MAY_USE_CELLID, false) ? "yes" : "no"));
	        }
	        {
	          TextView tv = (TextView)findViewById(R.id.max_interval);
	          tv.setText(Preferences.getFieldName(Preferences.MAX_POLLING_INTERVAL) +
	                ": " + prefs.getString(Preferences.MAX_POLLING_INTERVAL, "-1"));
	        }
	        {
	          TextView tv = (TextView)findViewById(R.id.min_interval);
	          tv.setText(Preferences.getFieldName(Preferences.MIN_POLLING_INTERVAL) +
	                ": " + prefs.getString(Preferences.MIN_POLLING_INTERVAL, "-1"));
	        }
	  }


	  @Override
	  public boolean onCreateOptionsMenu(Menu menu)
	  {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.main_menu, menu);
	        menu.add(0, R.layout.main, 0, "Quit");
	        return true;
	  }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
            switch (item.getItemId())
            {
            case R.id.preferences:
            	startActivity(new Intent(MainScreen.this, Preferences.class));
            	break;
            case R.id.db_screen_menu:
            	startActivity(new Intent(MainScreen.this, DBScreen.class));
            	break;
            case R.id.map_screen_menu:
            	startActivity(new Intent(MainScreen.this, MapScreen.class));
            	break;
            case R.layout.main:
            	stopService(new Intent(this, Oracle.class));
            	finish();
            	break;
            default:
            }
            return true;
    }


	  public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
	  {
		  print_prefs(prefs);
	  }

}
